#!/bin/bash

# Get the directory of the script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Check if the correct number of arguments are provided
if [ "$#" -lt 4 ]; then
    echo "Usage: $0 -i <input_directory> -o <output_directory> [-c <config_file>] [-l]"
    exit 1
fi

# Initialize variables
input_dir=""
output_dir=""
config_file=""
run_in_output=false

# Parse arguments
while getopts ":i:o:c:l" opt; do
    case ${opt} in
        i )
            input_dir=$(realpath "$OPTARG")  # Convert to absolute path
            ;;
        o )
            output_dir=$(realpath "$OPTARG")  # Convert to absolute path
            ;;
        c )
            config_file=$(realpath "$OPTARG")  # Convert to absolute path
            ;;
        l )
            run_in_output=true  # Set flag to run in output directory
            ;;
        \? )
            echo "Invalid option: $OPTARG" 1>&2
            exit 1
            ;;
        : )
            echo "Invalid option: $OPTARG requires an argument" 1>&2
            exit 1
            ;;
    esac
done

# Check if the input directory exists
if [ ! -d "$input_dir" ]; then
    echo "Input directory does not exist: $input_dir"
    exit 1
fi

# Check if the output directory exists; create if it does not
if [ ! -d "$output_dir" ]; then
    mkdir -p "$output_dir"
fi

# Change to the script directory
cd "$SCRIPT_DIR"

# Check if the service is built; if not, build it
if [ ! "$(docker-compose ps -q c2rust-dev)" ]; then
    echo "Building the Docker Compose service..."
    docker-compose build
fi

# Prepare the command
command="/app/cherncvenv/bin/chernc2rust -i /app/dockerinput -o /app/dockeroutput --codeql /codeql/codeql"

# If a config file is provided, modify the command
if [ -n "$config_file" ]; then
    # Check if the configuration file exists
    if [ ! -f "$config_file" ]; then
        echo "Configuration file does not exist: $config_file"
        exit 1
    fi
    # Add config to command
    command="$command -c /app/dockerconfig/$(basename "$config_file")"
else
    command="$command -c /app/chernc_configs.yml"
fi

# Run the Docker Compose command
if [ "$run_in_output" = true ]; then
    # Change the working directory to /app/output
    docker compose run --rm \
        -v "$input_dir:/app/dockerinput" \
        -v "$output_dir:/app/dockeroutput" \
        ${config_file:+-v "$config_file:/app/dockerconfig/$(basename "$config_file")"} \
        c2rust-dev sh -c "cd /app/dockeroutput && $command"
else
    # Run without changing the working directory
    docker compose run --rm \
        -v "$input_dir:/app/dockerinput" \
        -v "$output_dir:/app/dockeroutput" \
        ${config_file:+-v "$config_file:/app/dockerconfig/$(basename "$config_file")"} \
        c2rust-dev $command
fi
